package main

import (
	"bufio"
	"dxmtools"
	"flag"
	"fmt"
	"imgdown/fetcher"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
)

func main1(){
	fmt.Println("User Age is ",18)
	imgurl := "http://b336.photo.store.qq.com/psb?/a2748d16-3d8b-47bb-984d-3126b373942c/khPWlzzblvfSYSxBgnkBoUKQiyYtCY6gX7UHhmoyQxE!/b/dBQqSsgeMAAA&bo=gAJYAwAAAAABB*k!"
	resp,err := http.Get(imgurl)
	if err != nil {
		log.Println(err)
		return
	}
	defer resp.Body.Close()

	reader := bufio.NewReaderSize(resp.Body,32*1024)
	newFilePath := "D:\\"
	fileName := "2.jpeg"
	file,err := os.Create(newFilePath+fileName)
	writer := bufio.NewWriterSize(file,32*1024)

	size,_ := io.Copy(writer,reader)

	defer writer.Flush()
	dxmtools.SetMachineId(1)
	id := dxmtools.GetSnowflakeId()
	fmt.Println("Id: ",id)
	fmt.Println("Size: ",size)


}

var wg sync.WaitGroup

func main02(){
	in := make(chan  int,200)


	for i := 0 ;i<10;i++ {
		go func() {
			for {
				id := <-in
				fmt.Println("InId: ", id)
				wg.Done()
			}
		}()
	}


	for index:=0;index < 100;index++{
		wg.Add(1)
		in <- index
	}

	wg.Wait()
	fmt.Println("is ok")
}


var (
	InputFileFlag = flag.String("i","img.txt","img url input file")
	HelpFlag = flag.Bool("h", false, "show useage ")
	OutDirFlag = flag.String("o","./imgs","where img to be store")
	ConcurrentFlag = flag.Int("C",20,"concurrent num ")
	ResLogFlag = flag.String("log","imgs.log","log result info ")
	MethodFlag = flag.String("m","GET","Http Method Get")
	HeaderFileFlag = flag.String("hf","header.txt","header file ")
)


var useage = `
-i set img input file default ./img.txt
-h help
-C download concurrent thread num default 20
-log log result info default ./imgs.log
-o where img to be store default ./imgs
-m http method default get
-hf http header file default header.txt

nameid demo file123_a_b_c this will mkdir a/b/c/ under args -o  then file123 will store in it
`

func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func parseHeaderFile(hf string) map[string]string{
	hmap := map[string]string{}
	hfile,err := os.Open(hf)
	if err != nil {
		log.Println(err)
		return hmap
	}
	hfileReader := bufio.NewReader(hfile)
	for{
		line,err := hfileReader.ReadString('\n')
		if err != nil || err == io.EOF{
			break
		}
		line = strings.TrimSpace(line)
		lineList := strings.Split(line,":")
		if len(lineList) > 1{
			key := strings.TrimSpace(lineList[0])
			value := strings.TrimSpace(lineList[1])
			hmap[key] = value
		}
	}
	return hmap
}
func  main()  {
	flag.Parse()
	if *HelpFlag {
		fmt.Println(useage)
		return
	}




	exists,_ := dxmtools.PathExists(*InputFileFlag)
	if !exists{
		panic(fmt.Sprintf("input file is not exists: %s ",*InputFileFlag))
		return
	}
	outdirExists,_ := dxmtools.PathExists(*OutDirFlag)
	if !outdirExists{
		err := os.MkdirAll(*OutDirFlag,os.ModePerm)
		if err != nil{
			panic(err)
		}
	}




	inputFile,err := os.Open(*InputFileFlag)
	if err != nil {
		panic(err)
	}
	defer inputFile.Close()

	logFile,err := os.Create(*ResLogFlag)
	if err != nil {
		panic(err)
	}
	defer logFile.Close()

	out := make(chan int)
	in :=  make(chan fetcher.ImgInfo)

	headerMap := parseHeaderFile(*HeaderFileFlag)
	for index := 0 ;index < *ConcurrentFlag;index++{
		fetcher.StartInTask(in,*OutDirFlag,logFile,out,*MethodFlag,headerMap)
	}

	fileReader := bufio.NewReader(inputFile)
	totalNum := 0
	readEnd := false
	for !readEnd {
		line,err := fileReader.ReadString('\n')
		if err != nil || err == io.EOF{
			readEnd = true
		}
		fslist := strings.Fields(line)
		length := len(fslist)
		src := ""
		fileName := ""
		if length > 0{
			src = fslist[0]
			if !strings.HasPrefix(src,"http"){
				continue
			}
		}
		if length > 1{
			fileName = strings.TrimSpace(fslist[1])
		}
		if len(strings.TrimSpace(fileName)) == 0 {
			fileName = fmt.Sprintf("%d",dxmtools.GetSnowflakeId())
		}
		imgInfo := fetcher.ImgInfo{}
		imgInfo.Src = src
		imgInfo.NameId = fileName
		go func() {
			in <- imgInfo
		}()
		totalNum++
	}

	//wait all down goroute finish work
	receiveNum := 0
	for{
		<-out
		receiveNum++
		if receiveNum == totalNum {
			break
		}
	}


























}



